﻿using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using TraceabilityApp_Api.Application.Command.Traceability;
using TraceabilityApp_Api.DTO;
using TraceabilityApp_ErrorCode;



namespace TraceabilityApp_Api.Controllers
{
    /// <summary>
    /// 溯源基本信息控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TraceabilityController : ControllerBase
    {
        private readonly IMediator mediator;

        public TraceabilityController(IMediator mediator)
        {
            this.mediator = mediator;
        }
        /// <summary>
        /// 溯源基本信息显示查询
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        public Task<ApiPaging<TraceabilityDTO>> GetTraceability([FromQuery]GetTraceabilityCommand request)
        {
            return mediator.Send(request);
        }
        /// <summary>
        /// 溯源基本信息添加
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public Task<ApiResult<int>> AddTraceadility(AddTraceadilityCommand request)
        {
            return mediator.Send(request);
        }
        /// <summary>
        /// 溯源基本信息删除
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        public Task<ApiResult<int>> DelTraceadility([FromQuery]DelTraceadilityCommand request)
        {
            return mediator.Send(request);
        }
        /// <summary>
        /// 溯源基本信息修改
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public Task<ApiResult<int>> UpdateTraceadility(UpdateTraceadilityCommand request)
        {
            return mediator.Send(request);
        }
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<string>> UploadFile(IFormFile file)
        {
            var res = new ApiResult<string>();
            string saveDir = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "img");
            if (!Directory.Exists(saveDir))
                Directory.CreateDirectory(saveDir);

            string savefile = Path.Combine(saveDir, file.FileName);
            using (FileStream fs = new FileStream(savefile, FileMode.Create))
            {
                await file.CopyToAsync(fs);
                await fs.FlushAsync();
            }
            // 这里一定要有 /img/ 和斜杠
            string url = $"http://localhost:5153/img/{file.FileName}";
            return new ApiResult<string>()
            {
                Code = ApiEnum.OK,
                Msg = "上传成功",
                Data = url
            };
        }
    }
}
